/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trader.controller;

import hibernate.dao.DeliveryInstructionDao;
import hibernate.dao.DeliveryInstructionMillDao;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mill.hibernate.dto.DeliveryInstruction_mill;
import mill.hibernate.dto.QualityReport_mill;
import mill.hibernate.dto.WeightNote_mill;
import pc.system.WServlet;
import trader.hibernate.blo.MediateBLO;
import trader.hibernate.dto.*;
import wstrader.Users;
import wstrader.task.trade.TradeTask;
import wstrader.task.traffic.di.Instruction;

/**
 *
 * @author kiendn
 */
public class DI_Controller extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            if (action.equals("getDIMillInfo")) {
                int trader_id = Integer.parseInt(request.getParameter("trader_id"));
                DeliveryInstruction_mill di_mill = new MediateBLO().find_mill_di(trader_id);
                if (di_mill != null) {
                    ArrayList<WeightNote_mill> wn_list = new DeliveryInstructionMillDao().get_wn_by_di_id(di_mill.getId());
                    //ArrayList<WN_QR_Group> new_group = new ArrayList<WN_QR_Group>();

                    for (int i = 0; i < wn_list.size(); i++) {
                        QualityReport_mill qr_mill = new DeliveryInstructionMillDao().get_qr(wn_list.get(i).getQrId());

                        QualityReport qr = new DeliveryInstructionMillDao().getQRfromMill(qr_mill);

                        WeightNote wn = new DeliveryInstructionMillDao().getWNfromMill(wn_list.get(i));

                        //new_group.add(new WN_QR_Group(wn, qr));

                        int qr_id = new DeliveryInstructionDao().getQrId(qr_mill);

                        if (qr_id > 0) {//qr exist
                            //just update get qr_id and wn_id and update them.
                            qr.setId(qr_id);
                            DeliveryInstructionDao Di_dao = new DeliveryInstructionDao();
                            Di_dao.updateQr(qr);
                            int wn_id = new DeliveryInstructionDao().getWnId(wn_list.get(i));
                            wn.setId(wn_id);
                            Di_dao.updateWn(wn);
                        } else {//qr doesn't exist
                            //create new qr first then add new qr id into wn and create new wn.
                            DeliveryInstructionDao di_dao = new DeliveryInstructionDao();
                            int new_qr_id = di_dao.saveQr(qr);
                            wn.setRefNumber(di_dao.getNewWnRef());
                            wn.setQrId(new_qr_id);
                            wn.setInstId(di_dao.getTraderDiId(di_mill.getId()));
                            int new_wn_id = di_dao.saveWn(wn);
                            di_dao.save_to_QrWn(new Mediate(new_qr_id, qr_mill.getId(), "QR", di_mill.getWarehouseId()));
                            di_dao.save_to_QrWn(new Mediate(new_wn_id, wn_list.get(i).getId(), "WN", di_mill.getWarehouseId()));
                        }
                    }

                }
                //out.println(1);
            } else if (action.equals("convert")) {
                DeliveryInstructionMillDao dao = new DeliveryInstructionMillDao();
//        String new_ref = dao.getNewRef();
//        int new_id = dao.getNewDI_id();
                ArrayList<DeliveryInstruction_mill> list = dao.getAllDI();
                for (int i = 0; i < list.size(); i++) {
                    System.out.println(list.get(i).getId() + "-" + list.get(i).getSupplierRef());
                    int contract_id = new DeliveryInstructionDao().getContractId(list.get(i).getSupplierRef());
                    if (contract_id > 0) {

                        Date date = list.get(i).getDate();
                        Date time = list.get(i).getTime();
                        //Integer contractId = 0;
                        Short supplierId = list.get(i).getSupplierId();
                        String supplierRef = list.get(i).getSupplierRef();
                        Short buyerId = list.get(i).getBuyerId(); //SW Commodities
                        String buyerRef = list.get(i).getBuyerRef();
                        Date deliveryDate = list.get(i).getDeliveryDate();
                        Date fromTime = list.get(i).getFromTime();
                        Date toTime = list.get(i).getToTime();
                        Short gradeId = list.get(i).getGradeId();
                        Double tons = list.get(i).getTons();
                        Short packingId = list.get(i).getPackingId();
                        Float kgPerBag = list.get(i).getKgPerBag();
                        Short noOfBags = list.get(i).getNoOfBags();
                        Short deliveredBags = list.get(i).getDeliveredBags(); // don't know, just leave it zero (by kiendn 6/11)
                        Byte warehouseId = list.get(i).getWarehouseId();
                        String markingOnBags = list.get(i).getMarkingOnBags();//can't find where it is (by kiendn 6/11)
                        Short weightControllerId = list.get(i).getWeightControllerId();
                        Short qualityControllerId = list.get(i).getQualityControllerId();
                        Short originId = list.get(i).getOriginId();
                        Short userId = 19; // stand for trade.
                        Byte status = list.get(i).getStatus();
                        String description = list.get(i).getDescription();
                        String remark = list.get(i).getRemark();
                        Short a = 0;
                        String new_ref = new DeliveryInstructionDao().getNewDIRef();

                        DeliveryInstruction trader_di = new DeliveryInstruction(new_ref, date, time, contract_id, supplierId, supplierRef, buyerId, buyerRef, deliveryDate, fromTime, toTime, gradeId, tons, packingId, kgPerBag, noOfBags, deliveredBags, warehouseId, markingOnBags, a, a, a, weightControllerId, qualityControllerId, userId, status, description, remark);

                        int inst_id = new DeliveryInstructionDao().saveDI(trader_di);

                        new DeliveryInstructionDao().save_to_mediate(new TraderdiMilldi(inst_id, list.get(i).getId(), warehouseId));

                        ArrayList<WeightNote_mill> wn_list = new DeliveryInstructionMillDao().get_wn_by_di_id(list.get(i).getId());
                        for (int j = 0; j < wn_list.size(); j++) {

                            //String new_wn_ref = 
                            QualityReport_mill qr_mill = new DeliveryInstructionMillDao().get_qr(wn_list.get(j).getQrId());

                            //qr_mill.setRefNumber(new DeliveryInstructionDao().getNewQrRef());

                            Character type = qr_mill.getType();
                            String refNumber = qr_mill.getRefNumber();
                            Date qr_date = qr_mill.getDate();
                            Date qr_time = qr_mill.getTime();
                            Byte qr_status = qr_mill.getStatus();
                            Float aboveSc20 = qr_mill.getAboveSc20();
                            Float sc20 = qr_mill.getSc20();
                            Float sc19 = qr_mill.getSc19();
                            Float sc18 = qr_mill.getSc18();
                            Float sc17 = qr_mill.getSc17();
                            Float sc16 = qr_mill.getSc16();
                            Float sc15 = qr_mill.getSc15();
                            Float sc14 = qr_mill.getSc14();
                            Float sc13 = qr_mill.getSc13();
                            Float sc12 = qr_mill.getSc12();
                            Float belowSc12 = qr_mill.getBelowSc12();
                            Float black = qr_mill.getBlack();
                            Float broken = qr_mill.getBroken();
                            Float blackBroken = qr_mill.getBlackBroken();
                            Float brown = qr_mill.getBrown();
                            Float moisture = qr_mill.getMoisture();
                            Float oldCrop = qr_mill.getOldCrop();
                            Float excelsa = qr_mill.getExcelsa();
                            Float floater = qr_mill.getFloater();
                            Float foreignMatter = qr_mill.getForeignMatter();
                            Float worm = qr_mill.getWorm();
                            Float moldy = qr_mill.getMoldy();
                            String cupClass = qr_mill.getCupClass();
                            Integer sampleDtsId = qr_mill.getSampleDtsId();
                            String qr_remark = qr_mill.getRemark();
                            Short qr_userId = 19;
                            Date completedDate = qr_mill.getCompletedDate();

                            QualityReport qr = new QualityReport(type, refNumber, qr_date, qr_time, qr_status, aboveSc20, sc20, sc19, sc18, sc17, sc16, sc15, sc14, sc13, sc12, belowSc12, black, broken, blackBroken, brown, moisture, oldCrop, excelsa, floater, foreignMatter, worm, moldy, cupClass, sampleDtsId, qr_remark, qr_userId, completedDate);

                            int qr_id = new DeliveryInstructionDao().saveQr(qr);

                            if (qr_id > 0) {
                                wn_list.get(j).setQrId(qr_id);
                            }

                            //wn_list.get(j).setRefNumber(new DeliveryInstructionDao().getNewWnRef());

                            WeightNote wn = new DeliveryInstructionMillDao().getWNfromMill(wn_list.get(j));

                            wn.setInstId(inst_id);

                            DeliveryInstructionDao trader_dao = new DeliveryInstructionDao();

                            int new_wn_id = trader_dao.saveWn(wn);

                            boolean new_dt = new DeliveryInstructionDao().save_to_QrWn(new Mediate(qr_id, qr_mill.getId(), "QR", warehouseId));
                            new_dt = new DeliveryInstructionDao().save_to_QrWn(new Mediate(new_wn_id, wn_list.get(j).getId(), "WN", warehouseId));


                        }
                    }


                    //Users user = new Users(WServlet.getConnectionPool("wstrader"), "admin", "admin", "us");
                    //wstrader.task.traffic.di.Instruction task = user.traffic.di.dIns;
                    
                    //task.updatePendingReceiveField(list.get(i).getContractId());
                }
                out.println(1);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
